package com.milotnt.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.Date;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理所有异常
     */

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code", "500");
        modelAndView.addObject("error", "系统异常");
        modelAndView.addObject("message", e.getMessage());
        modelAndView.addObject("timestamp", new Date()); // 添加时间戳
        modelAndView.setViewName("error"); // 确保视图名称正确
        return modelAndView;
    }

    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    public ModelAndView handleNullPointerException(NullPointerException ex) {
        log.error("空指针异常: ", ex);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code", "500"); // 补充缺失的 code 属性
        modelAndView.addObject("error", "空指针异常"); // 补充 error 属性
        modelAndView.addObject("message", "系统发生空指针异常，请联系管理员");
        modelAndView.addObject("timestamp", new Date()); // 添加时间戳
        modelAndView.setViewName("error"); // 统一视图名称
        return modelAndView;
    }


    //处理文件流异常
    @ExceptionHandler(IOException.class)
    public ModelAndView handleIOException(IOException e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("code", "500");
        modelAndView.addObject("error", "文件操作异常");
        modelAndView.addObject("message", "文件上传或读取失败，请检查文件权限和路径");
        modelAndView.addObject("timestamp", new Date());
        modelAndView.setViewName("error");
        log.error("文件操作异常: ", e);
        return modelAndView;
    }
}
